package io.bloom.site.util;

import io.bloom.site.exception.BizRTException;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.lang.random.R;

import javax.servlet.http.HttpSession;

import java.util.Collection;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.nutz.lang.Lang.md5;

/**
 * AppUtil
 *
 * @author T_T
 * @since 18/11/2017 21:10
 */
public class AppUtil {

    public static boolean isLogin(HttpSession session) {
        return null != session.getAttribute("user");
    }

    public static String random(int max, String str) {
        return R.random(1, max) + str;
    }

    public static boolean enableCdn() {
        return true;
    }

    public static String gravatar(String email) {
        if (!enableCdn()) {
            return "/static/admin/images/unicorn.png";
        }
        String avatarUrl = "https://cn.gravatar.com/avatar";
        if (Strings.isBlank(email)) {
            return avatarUrl;
        }
        String hash = md5(email.trim().toLowerCase());
        return avatarUrl + "/" + hash;
    }


    public static String fmtdate(Date date){
        return Times.sD(date);
    }


    private static final String[] COLORS = {
            "default",
            "primary",
            "success",
            "info",
            "warning",
            "danger",
            "inverse",
            "purple",
            "pink"
    };

    public static String randColor() {
        int r = R.random(0, COLORS.length - 1);
        return COLORS[r];
    }


    public static boolean isEmpty(Collection object) {
        return object == null || object.size() == 0;
    }

    private static final Pattern SLUG_REGEX = Pattern.compile("^[A-Za-z0-9_-]{5,100}$", Pattern.CASE_INSENSITIVE);
    public static boolean isPath(String slug) {
        if (Strings.isNotBlank(slug)) {
            if (slug.contains("/") || slug.contains(" ") || slug.contains(".")) {
                return false;
            }
            Matcher matcher = SLUG_REGEX.matcher(slug);
            return matcher.find();
        }
        return false;
    }


    public static void validate(boolean expectedExpress, String errorMessage) {
        if (!expectedExpress) {
            throw new BizRTException(errorMessage);
        }
    }

}
